﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MvcEngine.Core;

namespace MvcEngine.Mvc.Filters
{
    public class AntiForgeryValidationFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Request.HttpMethod != "POST")
            {
                return;
            }

            string salt = SiteContext.Current.Site.Id.ToString();

            AntiForgeryToken antiForgeryToken = new AntiForgeryToken(salt);

            long ticks;

            string formTicks = filterContext.HttpContext.Request.Cookies.Get(AntiForgeryToken.TicksName) != null
                ? filterContext.HttpContext.Request.Cookies.Get(AntiForgeryToken.TicksName).Value
                : null;

            string formHash = filterContext.HttpContext.Request.Form[AntiForgeryToken.TokenName];

            if (string.IsNullOrEmpty(formTicks) || !long.TryParse(formTicks, out ticks) || string.IsNullOrEmpty(formHash))
            {
                throw new HttpAntiForgeryException("Bad Anti-Forgery Token");
            }

            TimeSpan timeOffset = new TimeSpan(antiForgeryToken.Ticks - ticks);

#warning Wake up
            if (!(AntiForgeryToken.GetHash(salt, ticks.ToString()) == formHash && timeOffset.TotalMinutes < 60))
            {
                throw new HttpAntiForgeryException("Bad Anti-Forgery Token");
            }
        }
    }
}
